#!/bin/bash

## use this script to create or drop db

MUSER="$1"
MPASS="$2"
MDB="$3"
CMD="$4"
 
# Detect paths
MYSQL=$(which mysql)
AWK=$(which awk)
GREP=$(which grep)
 
if [ $# -ne 4 ]
then
	echo "Usage: $0 {MySQL-User-Name} {MySQL-User-Password} {MySQL-Database-Name} {command}"
	echo "    init    Create a new database schemal, no any tables in it "
	echo "    del     Drops all tables from a MySQL"
	echo "    clear   Clear all data from tables"
	echo "    drop    Drops database schemal from a MySQL"
	exit 1
fi
 
if [ "$CMD" = 'init' ]; then
    echo "Create a new database named $MDB ..." 
    echo "SQL: create database $MDB character set utf8 collate utf8_general_ci"
    $MYSQL -u $MUSER -p$MPASS -e "CREATE DATABASE $MDB CHARACTER SET UTF8 COLLATE utf8_general_ci"
    exit 1
fi

TABLES=$($MYSQL -u $MUSER -p$MPASS $MDB -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )
 
if [ "$CMD" = 'del' ]; then
    for t in $TABLES
    do
        echo "Deleting $t table from $MDB database..."
        $MYSQL -u $MUSER -p$MPASS $MDB -e "drop table $t"
    done
elif [ "$CMD" = 'clear' ]; then 
    for t in $TABLES
    do 
	echo "Clear data from table $t in database $MDB ..."
	$MYSQL -u $MUSER -p$MPASS $MDB -e "delete from $t" 
    done	
elif [ "$CMD" = 'drop' ]; then
    echo "drop database $MDB ..."
    $MYSQL -u $MUSER -p$MPASS $MDB -e "drop database $MDB"	
else
    echo "$CMD command not found"
    exit 1
fi

## origin shell script
#for t in $TABLES
#do
#	echo "Deleting $t table from $MDB database..."
#	$MYSQL -u $MUSER -p$MPASS $MDB -e "drop table $t"
#done

